var Ow = require("./api_onewire");
var ow = new Ow("localhost", 4304);

var Db = require("../resources/database");
db = new Db();

function findOwid(id, cb)
{
    db.devices.findOne( {id: id, protocol: 'ow'}, function(error, data){
        if(error){
            cb(error);
        } else if( data )
        {
            cb(null, data);
        } else{
            cb(null, null, id);
        }
    });
}

function ping_ow_devices(host){
    console.log("reload ow meters");
    try {
     ow.dir("/",function(directories){
        console.log(directories);
        for(var i=0;i<directories.length;i++){
            var id = directories[i];
            if( id[0] == '/' && id[3] == '.' && id.length>14  )
            {
                id = id.replace("/","");	
                //console.log("Founded device %s, check if its already in db", id);
                findOwid(id, function(error, device, id){
                    if( error ){
                    } else if( device ){
                         //console.log("id "+device.id+" is already in db");
                    } else {
                        console.log("New OW sensor detected with id "+id);
                        var device = {
                            protocol: 'ow',
                            type: 'meter',
                            id: id
                        };
                        db.devices.create(device, function(error, data){
                            console.log(error);
                            console.log(data);
                            db.events.create( {
                                    msg: error?'OW device creation failed':'new ow-device detected with id: '+data.id,
                                    details: error?error:null, 
                                    type: error?'fatal':'general',
                                    source: {
                                        component: 'onewire-service',
                                    }
                                }, function(){});
                        });
                    }
                });
            } 
        }
        //queue for next ping in the next predefined interval
     });
    } catch(e) {
        console.log("OwException");
        console.log(e); 
    }
}
function isNumber (o) {
  return ! isNaN (o-0) && o != null;
}
function measure(device, callback)
{
    var path = "/"+device.id+"/temperature";
    console.log("Reading device: "+path);
    try {
       ow.read(path, function(result){
            if( isNumber(result) ){
                console.log("result: %d", result);
                var data = {unit: 'C', value: result}
                db.devices.events.create({device: device.uuid, values: [data]}, callback );
            }
            else{ 
                console.log("Invalid value");
                callback('fail', device);
            }
        });
        
    } catch(e) {
        console.log("OwException");
        console.log(e);
        callback(e, device);
    }
}
function read_ow_meters(){

    db.devices.find({protocol: 'ow', enable: true}, function(error, devs){
        if(error){
            console.log("getDevicesByProtocol::error");
            console.log(error);
        }
        else {
            for(var i=0;i<devs.length;i++){
               measure( devs[i], function(error, device){
                    if( error ){
                        db.devices.update( {uuid: device.uuid}, {enable: false}, function(){});
                        db.events.create( {
                            msg: 'Fails on read ow device '+device.id+". Sensor Disabled. Check connection! ",
                            details: error, 
                            type: 'fatal',
                            source: {
                                component: 'onewire-service',
                            }
                        }, function(){});
                    }
               });
       
                //var cmd = "-t C N:"+ result;
                //console.log(cmd);
                //rrd.rrdExec( "update",  cmd, function(err){
                //    if(err){
                //        console.log(err);
                //    }
                //    else console.log("update success");
                //});
            }
        }
    });
}

function OwService() {
    this.ping = {id: undefined, interval: 10000};
    this.read = {id: undefined, interval: 10000};
    
}

OwService.prototype.start = function(ping_interval_s, read_interval_s){
    if(ping_interval_s) this.ping.interval = ping_interval_s*1000;
    if(read_interval_s) this.read.interval = read_interval_s*1000;
    this.ping.id = setInterval (ping_ow_devices, this.ping.interval);
    this.read.id = setInterval (read_ow_meters, this.read.interval);
    
}
OwService.prototype.stop = function(){
    //clearInterval(this.ping.id);
    clearInterval(this.read.id);
}
// export the class
module.exports = OwService;